package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sl.au.entity.Account;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ChanceDelivery;
import com.sl.au.entity.ChanceManagerDelivery;
import com.sl.au.entity.JPushMsg;
import com.sl.au.entity.User;
import com.sl.au.service.AccountService;
import com.sl.au.service.ChanceDeliveryService;
import com.sl.au.service.ChanceFlowNodeService;
import com.sl.au.service.ChanceManagerDeliveryService;
import com.sl.au.service.ChanceService;
import com.sl.au.service.ExdeviExdePersonRoleInfoService;
import com.sl.au.service.JGPushService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;

@RestController
@RequestMapping(value = "/ui/managerDelivery")
public class ChanceManagerDeliveryController extends BaseController {

	@Autowired
	ChanceDeliveryService chanceDeliveryService;

	@Autowired
	SaleAreaService saleAreaService;

	@Autowired
	OptionService optionService;

	@Autowired
	ChanceManagerDeliveryService chanceManagerDeliveryService;

	@Autowired
	ChanceService chanceService;

	@Autowired
	UserService userService;

	@Autowired
	AccountService accountService;

	@Autowired
	OperateLogService operateLogService;

	@Autowired
	ChanceFlowNodeService chanceFlowNodeService;
	
	@Autowired
	ExdeviExdePersonRoleInfoService exdeviExdePersonRoleInfoService;
	
	@Autowired
	JGPushService jPushService;
	
	/**
	 * 销售信息服务器分页数据
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getManagerPage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String isReceived = request.getParameter("state");
		Account a = this.getMyAccount();
		if (key==null)
			key="";
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		String userArea = a.getUser().getSaleArea().getAreaName();
		condition.put("userSuperior", userSuperior);
		condition.put("userArea", userArea);
		condition.put("key", key);
		condition.put("isReceived", isReceived);
		List<ChanceDelivery> saleChances = chanceDeliveryService.getManagerPage(start, length, condition, null, null);
		Long count = 0l;
			count = chanceDeliveryService.getRepository().getAllManagerChanceCount(userSuperior, userArea, key,isReceived);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 销售信息服务器分页数据
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getManagerPage1", method = RequestMethod.GET)
	public Map<String, Object> getPage1(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String isReceived = request.getParameter("state");
		int targetType = Integer.parseInt(request.getParameter("targetType"));
		Account a = this.getMyAccount();
		if (key==null)
			key="";
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		String userArea = a.getUser().getSaleArea().getAreaName();
		condition.put("userSuperior", userSuperior);
		condition.put("userArea", userArea);
		condition.put("key", key);
		condition.put("isReceived", isReceived);
		List<ChanceDelivery> saleChances = chanceDeliveryService.getManagerPage(start, length, condition,targetType, null, null);
		Long count = 0l;
		if(targetType == 4){
			count = chanceDeliveryService.getRepository().getAllManagerChanceCount(userSuperior, userArea, key,isReceived);
		}else{
			count = chanceDeliveryService.getRepository().getAllManagerChanceCount(userSuperior, userArea, key,isReceived,targetType);
		}
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * 分配员工弹窗保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/distribute", method = RequestMethod.POST)
	public Map<String, Object> managerDeliveryChance(HttpServletRequest request,
			@RequestBody ChanceManagerDelivery chanceManagerDelivery) {
		Map<String, Object> map = new HashMap<String, Object>();
		chanceManagerDeliveryService.getRepository().save(chanceManagerDelivery);
		Account a = this.getMyAccount();
		User user = a.getUser();
		Chance saleChance = chanceService.getRepository().findOne(chanceManagerDelivery.getSaleChance().getId());
		User staff = userService.getRepository().findOne(chanceManagerDelivery.getUser().getId());
		String chanceName = saleChance.getName();
		
		List<String> list = new ArrayList<>();
		list.add(ExdeUtil.splitString(staff.getId()));
		System.out.println("员工"+staff.getName());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "分配给" + staff.getName());
		msg.setTitle("信息" + chanceName);
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "分配销售信息【" + chanceName + "】给员工【" + staff.getEmpLogin().getUserName() + "】";
		operateLogService.log(user, "信息分配员工", content);
		//写入流转记录
		chanceFlowNodeService.flow(user, saleChance, user.getEmpLogin().getUserName(), staff.getEmpLogin().getUserName()+"("+staff.getSaleArea().getAreaName()+")", "信息分配员工");
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}

	/**
	 * 验证是否已分配选中员工
	 * 
	 * @return
	 */
	@RequestMapping(value = "/validUser", method = RequestMethod.GET)
	public Map<String, Object> validUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceId = request.getParameter("chanceId");
		String userId = request.getParameter("userId");
		ChanceManagerDelivery chanceManagerDelivery = chanceDeliveryService.getRepository().validUser(chanceId, userId);
		int isDelivery = 0;
		if (chanceManagerDelivery != null) {
			isDelivery = 1;
		}
		map.put("isDelivery", isDelivery);
		return map;
	}

	// 删除已分配员工
	@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
	public Map<String, Object> deleteUser(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<ChanceManagerDelivery> chanceManagerDeliverys = new ArrayList<ChanceManagerDelivery>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		
		for (int i = 0; i < id.length; i++) {
			String managerId = id[i];
			ChanceManagerDelivery chanceManagerDelivery = new ChanceManagerDelivery();
			chanceManagerDelivery.setId(managerId);
			chanceManagerDeliverys.add(chanceManagerDelivery);
			//保存日志
			ChanceManagerDelivery chanceManager = chanceManagerDeliveryService.getRepository().findOne(managerId);
			String userId = chanceManager.getUser().getId();
			User staff = userService.getRepository().findOne(userId);
			String chanceName = chanceManager.getSaleChance().getName();
			String content = "销售信息【" + chanceName + "】从员工【" + staff.getEmpLogin().getUserName() + "】处撤回";
			operateLogService.log(user, "信息分配员工", content);
			//写入流转记录
			chanceFlowNodeService.flow(user, chanceManager.getSaleChance(), user.getEmpLogin().getUserName(), staff.getEmpLogin().getUserName()+"处撤回", "信息分配员工撤回");
		}
		chanceManagerDeliveryService.getRepository().deleteInBatch(chanceManagerDeliverys);
		map.put("code", 0);
		return map;
	}

	/**
	 * 分配员工弹窗分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getModulePage", method = RequestMethod.GET)
	public Map<String, Object> getModulePageCoop(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		Account a = this.getMyAccount();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String chanceId = request.getParameter("chanceId");
		String areaId = a.getUser().getSaleArea().getId();
		List<ChanceManagerDelivery> users = null;
		condition.put("chanceId", chanceId);
		condition.put("areaId", areaId);
		users = chanceManagerDeliveryService.getModulePage(start, length, condition, null, null);
		Long count = chanceManagerDeliveryService.getRepository().getModuleUserCount(chanceId, areaId);

		map.put("data", users);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 退回信息弹窗保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/rejectSave", method = RequestMethod.POST)
	public Map<String, Object> rejectChanceModule(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user=a.getUser();
		String deliveryId = request.getParameter("deliveryId");
		String rejectReason = request.getParameter("rejectReason");
		if (deliveryId != null || deliveryId != "") {
			ChanceDelivery chanceDelivery = chanceDeliveryService.getRepository().findOne(deliveryId);
			if (chanceDelivery != null) {
				chanceDelivery.setRejectReason(rejectReason);
				chanceDeliveryService.getRepository().save(chanceDelivery);
			}
			//写入流转记录
			chanceFlowNodeService.flow(user, chanceDelivery.getSaleChance(), user.getEmpLogin().getUserName(), user.getSaleArea().getSuperior(),"信息退回",rejectReason);
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 弹窗人员下拉框数据
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getStaff", method = RequestMethod.GET)
	public Map<Object, Object> getStaff(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		List<User> alluser = new ArrayList<User>();
		List<Account> accounts=accountService.getRepository().findAll();
		//lambda 表达式 感觉效率会高一些
		accounts.parallelStream()
				.filter(a -> (a.getRole().getName().indexOf("成套外勤") != -1 ||
						      a.getRole().getName().indexOf("销售外勤") != -1 ||
						      a.getRole().getName().indexOf("外贸内勤") != -1 ||
						      a.getRole().getName().indexOf("经理") != -1))
				.forEach(a -> alluser.add(a.getUser()));
//		for(Account a:accounts){
//			if (a != null) {
//				String role=a.getRole().getName();
//				if (role.indexOf("成套外勤") != -1 ||role.indexOf("销售外勤") != -1 || role.indexOf("外贸内勤") != -1 || role.indexOf("经理") != -1) {
//					alluser.add(a.getUser());
//				}
//			}
//		}
		map.put("alluser", alluser);
		return map;
	}
	/**
	 * 移动端获取未分配的职员
	 * 
	 * @return
	 */
	@RequestMapping(value = "/freeStaff", method = RequestMethod.GET)
	public Map<Object, Object> getFreeStaff(HttpServletRequest request) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		Account account=this.getMyAccount();
		List<User> alluser = new ArrayList<User>();
		String chanceId=request.getParameter("chanceId");
		List<Account> accounts=accountService.getRepository().findFreeStaff(chanceId,account.getUser().getSaleArea().getAreaName());
		//lambda 表达式 感觉效率会高一些
		accounts.parallelStream()
					.filter(a -> (a.getRole().getName().indexOf("成套外勤") != -1 ||
					a.getRole().getName().indexOf("销售外勤") != -1 ||
					a.getRole().getName().indexOf("外贸内勤") != -1 ||
					a.getRole().getName().indexOf("经理") != -1))
					.forEach(a -> alluser.add(a.getUser()));
//		for(Account a:accounts){
//			if (a != null) {
//				String role=a.getRole().getName();
//				if (role.indexOf("成套外勤") != -1 ||role.indexOf("销售外勤") != -1 || role.indexOf("外贸内勤") != -1 || role.indexOf("经理") != -1) {
//					alluser.add(a.getUser());
//				}
//			}
//		}
		map.put("alluser", alluser);
		return map;
	}
	
	/**
	 * 移动端分配员工保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/mobileDistribute", method = RequestMethod.POST)
	public Map<String, Object> managerDeliveryChanceMoblie(HttpServletRequest request,
			@RequestBody Map<String,Object> data) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceId=data.get("chanceId").toString();
		map.put("code", -1);
		if(!StringUtils.hasText(chanceId)) return map;
		Chance saleChance=chanceService.getRepository().findOne(chanceId);
		if(null==saleChance) return map;
		//跟新信息接收状态
		String chanceDeId=data.get("chanceDeId").toString();
		if(!StringUtils.hasText(chanceDeId)) return map;
		ChanceDelivery delivery=chanceDeliveryService.getRepository().findOne(chanceDeId);
		if(delivery.getIsReceived()!=1){
			delivery.setIsReceived(1);
			chanceDeliveryService.getRepository().save(delivery);
		}
		String chanceName = saleChance.getName();
		Account a = this.getMyAccount();
		User user = a.getUser();
		String userName=user.getEmpLogin().getUserName();
		@SuppressWarnings("unchecked")
		List<String> ids=(List<String>) data.get("ids");
		if(ids.isEmpty()) return map;
		for(String id:ids){
			ChanceManagerDelivery chanceManagerDelivery=new ChanceManagerDelivery();
			User staff=userService.getRepository().findOne(id);
			chanceManagerDelivery.setSaleChance(saleChance);
			chanceManagerDelivery.setUser(staff);
			chanceManagerDelivery.setIsReceived(0);
			chanceManagerDelivery.setTargetType(0);
			chanceManagerDeliveryService.getRepository().save(chanceManagerDelivery);
			String staffName=staff.getEmpLogin().getUserName();
			
			List<String> list = new ArrayList<>();
			list.add(ExdeUtil.splitString(staff.getId()));
			System.out.println("员工"+staff.getName());
			JPushMsg msg = new JPushMsg();
			msg.setAlias(list);
			msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "分配给" + staff.getName());
			msg.setTitle("信息" + chanceName);
			Map<String, String> extras = new HashMap<>();
			extras.put("ex1", "附加内容1");
			extras.put("ex2", "附加内容2");
			
			//写入日志记录
			String content = "分配销售信息【" + chanceName + "】给员工【" + staffName + "】";
			operateLogService.log(user, "信息分配员工", content);
			//写入流转记录
			chanceFlowNodeService.flow(user, saleChance, userName, staffName+"("+staff.getSaleArea().getAreaName()+")", "信息分配员工");
			jPushService.sendClient(msg, extras);
			
		}
		map.put("code", 0);
		return map;
	}
}